<script lang="ts" setup>
import { reactive } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useFs } from '@fast-crud/fast-crud';

import { BaseEmployeeApi } from '#/api';
import { BaseOrgApi } from '#/api/basic/user/baseOrg';
import { ScopeTypeEnum } from '#/enums/base';

import { createCrudOptions } from './data/crud';

defineOptions({
  name: '绑定角色',
  inheritAttrs: false,
});
const formData = reactive({
  scopeType: ScopeTypeEnum.EMPLOYEE,
  employeeId: '',
  orgId: '',
  bindRoleIds: [] as string[],
});

const { selectedRowKeys, crudRef, crudBinding, crudExpose } = useFs({
  createCrudOptions,
  context: formData,
});

const [Modal, modalApi] = useVbenModal({
  async onOpened() {
    const data = modalApi.getData();
    formData.scopeType = data.scopeType;
    if (data.scopeType === ScopeTypeEnum.EMPLOYEE) {
      formData.employeeId = data.id;
      formData.bindRoleIds = await BaseEmployeeApi.findEmployeeRoleByEmployeeId(
        formData.employeeId,
      );
    } else {
      formData.orgId = data.id;
      formData.bindRoleIds = await BaseOrgApi.findOrgRoleByOrgId(
        formData.orgId,
      );
    }

    // crudExpose.setSearchFormData({
    //   form: { orgId: data.id, scopeType: data.scopeType },
    // });
    crudExpose.doRefresh();
  },
  onClosed() {
    selectedRowKeys.value = [];
  },
  async onConfirm() {
    selectedRowKeys.value = [];
    modalApi.close();
  },
});

defineExpose(modalApi);
</script>

<template>
  <Modal title="绑定角色" class="h-full w-full">
    <FsCrud ref="crudRef" v-bind="crudBinding" />
  </Modal>
</template>
